package com.lsfb.duishangbaos.ShopManage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;

import com.lsfb.duishangbaos.Login.ShopEnter.LocationActivity;
import com.lsfb.duishangbaos.Login.ShopEnter.LocationEvent2;
import com.lsfb.duishangbaos.R;
import com.lsfb.duishangbaos.Utils.ListViewForScrollView;
import com.lsfb.duishangbaos.Utils.LittleUtils;
import com.lsfb.duishangbaos.Utils.Permission;
import com.lsfb.duishangbaos.Utils.PopWindowManager2;
import com.lsfb.duishangbaos.Utils.URLString;
import com.lsfb.duishangbaos.Utils.ZipPic;
import com.lsfb.duishangbaos.Utils.chooseimg.ChooseMoreImage;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.annotation.ContentView;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.net.HttpClient;
import com.zgscwjm.lsfbbasetemplate.utils.DensityUtils;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SN;
import com.zgscwjm.lsfbbasetemplate.utils.T;
import com.zgscwjm.lsfbbasetemplate.view.Camera.LsfbCamera;
import com.zgscwjm.lsfbbasetemplate.view.titlebar.LsfbTitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/5/10 0010.
 */
@ContentView(R.layout.aty_shop_manage)
public class ShopManageActivity extends LsfbActivity {

    @ViewInject(R.id.aty_rests_gridview)
    private GridView gridview;

    /**
     * 商家名称
     */
    @ViewInject(R.id.aty_shop_manage_et_name)
    private EditText et_name;

    /**
     * 商家简介
     */
    @ViewInject(R.id.aty_shop_manage_et_context)
    private EditText et_context;

    /**
     * 定位信息
     */
    @ViewInject(R.id.aty_shop_manage_text_dingwei)
    private TextView text_dingwei;

    /**
     * 门店地址
     */
    @ViewInject(R.id.aty_shop_manage_et_address)
    private EditText et_address;

    /**
     * 门店电话
     */
    @ViewInject(R.id.aty_shop_manage_et_phone)
    private EditText et_phone;

    /**
     * 定位经纬度
     */
    private String location = "";

    /**
     * 展示列表
     */
    @ViewInject(R.id.aty_listview)
    private ListViewForScrollView listview;

    private List<ShowBean> addShowList;

    private List<ShowViewBean> showViewlist;

    /**
     * 店铺照片
     */
    private String imgs = "";

    private List<ShopImgBean> mList;

    private GetShopAdapter adapter;

    private List<ShopShowBean.ListBean> showList;
    private ShowAdapter showAdapter;

    /**
     * 6.0权限管理类
     */
    private Permission permission;

    private Uri mUri;
    private String img_s = null;
    private int RESULT_VIDEO = 3;
    private int RESULT_CIR_IMAGE = 200;

    private String shop_id="0";

    private int img_add;

    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case 1000:
                    text_dingwei.setText(location);
                    break;
            }
        }
    };

    @Override
    public void initView() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        //相机权限
        permission = new Permission(this);
        permission.GetCAMEARPermission();

        LsfbTitleBar titlebar = LittleUtils.setsimpletitlebar(this, "店铺管理");
        TextView textView = LittleUtils.rightbtn(this, "发布");
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //收起软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et_name.getWindowToken(), 0);
                imm.hideSoftInputFromWindow(et_context.getWindowToken(), 0);

                editShop();

            }
        });
        titlebar.setRightView(textView, 0, 0, DensityUtils.dp2px(this, 10), 0);
        mList = new ArrayList<>();
        adapter = new GetShopAdapter(this, R.layout.item_shop_manage_img, mList);
        gridview.setAdapter(adapter);

        showList = new ArrayList<>();
        showViewlist=new ArrayList<>();
        showAdapter = new ShowAdapter(this, R.layout.item_shop_manage, showList,showViewlist);
        listview.setAdapter(showAdapter);
        addShowList = new ArrayList<>();


    }

    @Override
    public void initEvent() {

    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.aty_shop_manage_img_picture, R.id.aty_shop_manage_get_dingwei, R.id.aty_shop_manage_add_show})
    public void onClick(View view) {
        switch (view.getId()) {
            //店铺照片选择
            case R.id.aty_shop_manage_img_picture:

                final int tu_num = 4 - mList.size();
                if (mList.size() >= 4) {
                    SN.SnackShow(et_name, "最多只能选择四张图片哟");
                    return;
                }
                LittleUtils.code = -1;
                PopWindowManager2 popWindowManager = new PopWindowManager2(this,
                        R.layout.pop_selectcamrea) {
                    LsfbCamera mLsfbCamera = new LsfbCamera() {
                        @Override
                        public void resultUri(Uri uri) {
                            mUri = uri;
                        }
                    };

                    @Override
                    public void onViewLister(View contentView, final PopWindowManager2 manager) {
                        contentView.findViewById(R.id.pop_selectcamrea).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                mLsfbCamera.setActivity(ShopManageActivity.this);
                                mLsfbCamera.gotoCamera();
                                manager.hideWindow();
                            }
                        });
                        contentView.findViewById(R.id.pop_selectphoto).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(ShopManageActivity.this, ChooseMoreImage.class).putExtra("num", tu_num).putExtra("url", URLString.UPLOAD));
//                                Intent intent=new Intent(ShopManageActivity.this, ChooseMoreImage.class).putExtra("num", tu_num).putExtra("url", URLString.UPLOAD);
//                                startActivityForResult(intent, REQUEST_CODE);
                                manager.hideWindow();
                            }
                        });
                        contentView.findViewById(R.id.pop_bank).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                manager.hideWindow();
                            }
                        });

                    }
                };
                popWindowManager.showWindows(getWindow().getDecorView());
                popWindowManager.backgroundAlpha(this, 0.7f);
                break;
            //获取定位
            case R.id.aty_shop_manage_get_dingwei:
                startActivity(new Intent(this, LocationActivity.class));
                break;
            //增加展示
            case R.id.aty_shop_manage_add_show:
                ShopShowBean.ListBean postBean = new ShopShowBean.ListBean();
                postBean.setBewrite("");
                postBean.setId("0");
                postBean.setImg("");
                showViewlist.add(new ShowViewBean());
                showList.add(postBean);
                showAdapter.notifyDataSetChanged();
                break;

        }
    }

    @Override
    public void initData() {
        getShop();
    }

    /**
     * 获取店铺信息
     */
    public void getShop() {
        HashMap<String, String> hashMap = new HashMap<String, String>();

        new BaseInternet().getData_Get(URLString.SHOPREAD, hashMap, GetShopBean.class, new GetShopEvent<GetShopBean>(), true, false);
    }

    @EventAnnotation
    public void GetShopEvent(GetShopEvent<GetShopBean> event) {
        LsfbLog.e("sdasd");
        switch (event.getCode()) {
            case 200:

                shop_id=event.getData().getId();
                et_name.setText(event.getData().getSname());
                et_context.setText(event.getData().getBewrite());
                location = event.getData().getAxis();
                text_dingwei.setText(event.getData().getAxis());
                et_phone.setText(event.getData().getTel());

                imgs = event.getData().getImgs();
                mList.clear();
                String[] imgs = event.getData().getImgs().split(",");
                for (int n = 0; n < imgs.length; n++) {
                    ShopImgBean bean = new ShopImgBean();
                    bean.setImg(imgs[n]);
                    mList.add(bean);
                }
                adapter.notifyDataSetChanged();

                shopShow(event.getData().getId());
                break;
            default:
                SN.SnackShow(et_name, event.getMsg());
                break;
        }
    }

    /**
     * 获取店铺展示
     */
    public void shopShow(String sid) {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("sid", sid);
        new BaseInternet().getData_Get(URLString.SHOPSHOW, hashMap, ShopShowBean.class, new ShopShowEvent<ShopShowBean>(), true,false);
    }

    @EventAnnotation
    public void ShopShowEvent(ShopShowEvent<ShopShowBean> event) {
        LsfbLog.e("sda");
        switch (event.getCode()) {
            case 200:
                showList.clear();
                showViewlist.clear();
                initshowview(event.getData().getList());
                showAdapter.notifyDataSetChanged();
                break;
            default:
                SN.SnackShow(et_name, event.getMsg());
                break;
        }
    }

    public void initshowview(List<ShopShowBean.ListBean> list){
        for (int i = 0; i <list.size() ; i++) {
            ShowViewBean showview=new ShowViewBean();
            showViewlist.add(showview);
            showList.add(list.get(i));
        }
    }

    /**
     * 店铺编辑提交
     */
    public void editShop() {

        int ImgList_code = 0;
        int BewritesList_code = 0;

        String[] ids =new String[showList.size()];
        String[] img =new String[showList.size()];
        String[] bewrites =new String[showList.size()];

        for (int n = 0; n < showList.size(); n++) {
            if (showList.get(n).getId().isEmpty()) {
                ids[n]="0";
            } else {
                ids[n]=showList.get(n).getId();
            }
        }

        for (int m = 0; m < showList.size(); m++) {
            if (showList.get(m).getImg().isEmpty()) {
                ImgList_code = 1;
                break;
            } else {
                img[m]=showList.get(m).getImg();
            }
        }
        if (ImgList_code == 1) {
            SN.SnackShow(et_name, "店铺展示图片不能为空");
            return;
        }

        for (int k = 0; k < showList.size(); k++) {
            if (showList.get(k).getBewrite().isEmpty()) {
                BewritesList_code = 1;
                break;
            } else {
                bewrites[k]=showList.get(k).getBewrite();
            }
        }

        if (BewritesList_code == 1) {
            SN.SnackShow(et_name, "店铺展示描述不能为空");
            return;
        }
        String ibs_string="";
        String img_string = "";
        String bewrites_string = "";
        if (ids.length!=0) {
            for (int i = 0; i < ids.length; i++) {
                ibs_string = ibs_string + "," + ids[i];
            }
            ibs_string = ibs_string.substring(1);
        }

        if (img.length!=0) {
            for (int i = 0; i < ids.length; i++) {
                img_string = img_string + "," + img[i];
            }
            img_string = img_string.substring(1);
        }

        if (bewrites.length!=0) {
            for (int i = 0; i < ids.length; i++) {
                bewrites_string = bewrites_string + "," + bewrites[i];
            }
            bewrites_string = bewrites_string.substring(1);
        }


        imgs = "";
        for (int n = 0; n < mList.size(); n++) {
            imgs = imgs + "," + mList.get(n).getImg();
        }
        imgs = imgs.substring(1);
        if (et_name.getText().toString().isEmpty()) {
            SN.SnackShow(et_name, "请输入店铺名称");
            return;
        }
        if (et_context.getText().toString().isEmpty()) {
            SN.SnackShow(et_name, "请输入店铺简介");
            return;
        }
        if (location.isEmpty()) {
            SN.SnackShow(et_name, "请进行店铺定位");
            return;
        }
        if (et_phone.getText().toString().isEmpty()) {
            SN.SnackShow(et_name, "请输入店铺电话");
            return;
        }
        if (et_address.getText().toString().isEmpty()) {
            SN.SnackShow(et_name, "请输入店铺地址");
            return;
        }

        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("id", shop_id);
        hashMap.put("imgs", imgs);//图片集
        hashMap.put("sname", et_name.getText().toString());//店铺名称
        hashMap.put("bewrite", et_context.getText().toString());//店铺简介
        hashMap.put("axis", location+"|"+et_address.getText().toString());//店铺定位
        hashMap.put("tel", et_phone.getText().toString());//店铺电话
        if (ids.length != 0) {
//            hashMap.put("ids[]", new Gson().toJson(IdsList));//店铺展示id
            hashMap.put("ids", ibs_string);//店铺展示id
        }
        if (img.length != 0) {
            hashMap.put("img", img_string);//店铺展示图片
        }
        if (bewrites.length != 0) {
            hashMap.put("bewrites", bewrites_string);//店铺展示简介
        }
        new BaseInternet().getData(URLString.EDITSHOP, hashMap, EditShopBean.class, new EditShopEvent<EditShopBean>(), true);
    }

    @EventAnnotation
    public void EditShopEvent(EditShopEvent<EditShopBean> event) {
        LsfbLog.e("sda");
        switch (event.getCode()) {
            case 200:
                T.showShort(this, event.getMsg());
                finish();
                break;
            default:
                SN.SnackShow(et_name, event.getMsg());
                break;
        }
    }

    /**
     * 删除图片
     *
     * @param event
     */
    @EventAnnotation
    public void ShopImgDelEvent(final ShopImgDelEvent event) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                for (int n = 0; n < mList.size(); n++) {
                    if (mList.get(n).getImg().equals(event.getData())) {
                        mList.remove(n);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 获取定位
     *
     * @param event
     */
    @EventAnnotation
    public void LocationEvent2(LocationEvent2 event) {
        location = event.getData();
        handler.sendEmptyMessage(1000);
    }


    /**
     * 多图上传回调
     *
     * @param event
     */
    @EventAnnotation
    public void onEventPicGet(DuoTuEvent<String> event) {
        String img_duotu = event.getData();
        img_s = img_duotu;
        LsfbLog.e("多图上传:***" + img_s);
        String[] imgs = img_s.split(",");
        if (LittleUtils.code == -1) {
            for (String img : imgs) {
                if (!img.isEmpty()) {
                    ShopImgBean bean = new ShopImgBean();
                    bean.setImg(img);
                    mList.add(bean);
                }
            }
            adapter.notifyDataSetChanged();
        } else if (LittleUtils.code == 1) {
            showList.get(img_add).setImg(imgs[0]);
            showAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 照片回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (LittleUtils.code == -1) {
            if (requestCode == RESULT_CIR_IMAGE && resultCode == Activity.RESULT_OK
                    && null != data) {
                File file = LittleUtils.getImageToView(data);
                uploadimg(file);
            } else if (requestCode == LsfbCamera.REQUESTCODE && resultCode == RESULT_OK) {

                File file = new File(mUri.getPath());
                File zipfile = ZipPic.zippng(mUri.getPath());

                List lists = new ArrayList();
                lists.add(zipfile);
                new HttpClient().postFile(URLString.UPLOAD + LittleUtils.getToken(URLString.UPLOAD), new HashMap<String, String>(), lists, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        LsfbLog.e("照片上传成功");
                        String resultJson = response.body().string();
                        LsfbLog.e(resultJson);

                        try {
                            JSONObject jsonObject = new JSONObject(resultJson);
                            JSONObject img = jsonObject.getJSONObject("data");
                            String mimage = img.getString("img");

                            if (img_s == null) {
                                GetPhoto(mimage);
                                img_s = mimage;
                            } else {
                                if (mList.size() > 3) {
                                    SN.SnackShow(et_name, "最多只能上传4张照片");
                                } else {
                                    GetPhoto(mimage);
                                    img_s = img_s + "," + mimage;
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            LsfbLog.e("Json2解析错误" + e.getMessage());
                        }
                    }
                });
            }
        } else if (LittleUtils.code == 1) {

            if (requestCode == RESULT_CIR_IMAGE && resultCode == Activity.RESULT_OK
                    && null != data) {
                File file = LittleUtils.getImageToView(data);
                uploadimg(file);
            } else if (requestCode == LsfbCamera.REQUESTCODE && resultCode == RESULT_OK) {

                File file = new File(mUri.getPath());
                File zipfile = ZipPic.zippng(mUri.getPath());

                List lists = new ArrayList();
                lists.add(zipfile);
                new HttpClient().postFile(URLString.UPLOAD + LittleUtils.getToken(URLString.UPLOAD), new HashMap<String, String>(), lists, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        LsfbLog.e("照片上传成功");
                        String resultJson = response.body().string();
                        LsfbLog.e(resultJson);

                        try {
                            JSONObject jsonObject = new JSONObject(resultJson);
                            JSONObject img = jsonObject.getJSONObject("data");
                            String mimage = img.getString("img");
                            GetPhoto(mimage);
//                            showList.get(img_add).setImg(mimage);
//                            showAdapter.notifyDataSetChanged();

                        } catch (JSONException e) {
                            e.printStackTrace();
                            LsfbLog.e("Json2解析错误" + e.getMessage());
                        }
                    }
                });
            }
        }
    }

    /**
     * 上传单个图片
     *
     * @param file
     */
    public void uploadimg(File file) {
        HttpClient client = new HttpClient();
        List<File> fileList = new ArrayList<File>();
        fileList.add(file);
        client.postFile(URLString.UPLOAD + LittleUtils.getToken(URLString.UPLOAD), new HashMap<String, String>(), fileList, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LsfbLog.e("上传错误");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                LsfbLog.e("上传成功");

                String reAddress = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(reAddress);
                    String img_fm = jsonObject.getString("img");

                    if (LittleUtils.code == -1) {
                        ShopImgBean bean = new ShopImgBean();
                        bean.setImg(img_fm);
                        mList.add(bean);
                        adapter.notifyDataSetChanged();
                    } else if (LittleUtils.code == 1) {
                        showList.get(img_add).setImg(img_fm);
                        showAdapter.notifyDataSetChanged();
                    }

                } catch (JSONException e) {
                    LsfbLog.e(Log.getStackTraceString(e));
                    e.printStackTrace();
                }
            }
        });
    }

    public void GetPhoto(final String url) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (LittleUtils.code == -1) {
                    ShopImgBean bean = new ShopImgBean();
                    bean.setImg(url);
                    mList.add(bean);
                    adapter.notifyDataSetChanged();
                } else if (LittleUtils.code == 1) {
                    showList.get(img_add).setImg(url);
                    showAdapter.notifyDataSetChanged();
                }
            }
        });
    }


    /**
     * 删除展示item
     *
     * @param event
     */
    @EventAnnotation
    public void ShowDelEvent(ShowDelEvent event) {
        showList.remove(event.getData().intValue());
        showViewlist.remove(event.getData().intValue());
        showAdapter.notifyDataSetChanged();
    }

    /**
     * item上传图片
     *
     * @param event
     */
    @EventAnnotation
    public void ShowImgEvent(ShowImgEvent event) {
        LittleUtils.code = 1;
        img_add = event.getData().intValue();
        PopWindowManager2 popWindowManager = new PopWindowManager2(this,
                R.layout.pop_selectcamrea) {
            LsfbCamera mLsfbCamera = new LsfbCamera() {
                @Override
                public void resultUri(Uri uri) {
                    mUri = uri;
                }
            };

            @Override
            public void onViewLister(View contentView, final PopWindowManager2 manager) {
                contentView.findViewById(R.id.pop_selectcamrea).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mLsfbCamera.setActivity(ShopManageActivity.this);
                        mLsfbCamera.gotoCamera();
                        manager.hideWindow();
                    }
                });
                contentView.findViewById(R.id.pop_selectphoto).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(ShopManageActivity.this, ChooseMoreImage.class).putExtra("num", 1).putExtra("url", URLString.UPLOAD));
//                                Intent intent=new Intent(ShopManageActivity.this, ChooseMoreImage.class).putExtra("num", tu_num).putExtra("url", URLString.UPLOAD);
//                                startActivityForResult(intent, REQUEST_CODE);
                        manager.hideWindow();
                    }
                });
                contentView.findViewById(R.id.pop_bank).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        manager.hideWindow();
                    }
                });

            }
        };
        popWindowManager.showWindows(getWindow().getDecorView());
        popWindowManager.backgroundAlpha(this, 0.7f);

    }

    /**
     * item图片删除
     *
     * @param event
     */
    @EventAnnotation
    public void ShowImgDelEvent(ShowImgDelEvent event) {
        showList.get(event.getData().intValue()).setImg("");
        showAdapter.notifyDataSetChanged();
    }

}
